//
//  AppDelegate_iPhone.m
//  Tazama NGO
//
//  Created by jsheriff on 3/2/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "AppDelegate_iPhone.h"
#import "FieldObservationDB.h"
#import "MTLocationManager.h"
#import "ResourceRequisitionDB.h"
#import "KmlElementDB.h"
#import "PositionReportManager.h"
#import "Settings.h"
#import "MTStartupUtilities.h"

#import "SettingsViewController.h"

@interface AppDelegate_iPhone ()

- (void)checkRequiredUserDefaults;

@end

@implementation AppDelegate_iPhone

@synthesize window, tabBarController, areSettingsValid;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [MTStartupUtilities registerDefaultsFromSettingsBundle];
    if ([self areSettingsValid]) {
        
        NSLog(@"Required user defaults not found");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Required Settings" message:@"Please enter the host name, port, user ID, and full user name in settings." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"TazamaData.db"];
    
    [MTStartupUtilities copyFileFromBundleToDocumentsDirectory:@"TazamaData.db"];
    
    [[FieldObservationDB sharedInstance] initFromPath:dbPath];
    
    // Add the tab bar controller's view to the window and display.
    [window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    return YES;
}
- (void)checkRequiredUserDefaults {
    
    if (!self.areSettingsValid) {
        NSLog(@"Required user defaults not found");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Required Settings" message:@"Please enter the host name, port, user ID, and full user name in settings." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
    }
}
-(BOOL)areSettingsValid{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *postHost = [defaults objectForKey:kHostName];
    if (postHost.length == 0) return NO;
    
    NSString *feedURLStr = [defaults objectForKey:feedURL];
    if (feedURLStr.length == 0) return NO;
    
    NSString *email = [defaults objectForKey:kUserId];
    if (email.length == 0) return NO;
    
    NSString *kmlUpdateTime = [defaults objectForKey:kKmlFeedUpdatePeriod];
    if (kmlUpdateTime.length == 0 || [kmlUpdateTime intValue] < 10 || [kmlUpdateTime intValue] > 120) return NO;
    
    NSString *currCotTypeStr = [defaults objectForKey:currCoTType];
    if (currCotTypeStr.length == 0 || [currCotTypeStr isEqualToString:@"None"]) return NO;
    
    NSString *uidStr = [defaults objectForKey:uniqueID];
    if (uidStr.length == 0) return NO;
    
    NSString *sitrepKeywordStr = [defaults objectForKey:sitrepKeyword];
    if (sitrepKeywordStr.length == 0) return NO;
    
    NSString *posKeywordStr = [defaults objectForKey:posKeyword];
    if (posKeywordStr.length == 0) return NO;
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // Switch to the Settings app
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:"]];
    
    /*
    SettingsViewController *settingsController = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
    settingsController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:settingsController animated:YES];
    [settingsController release];
     */
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] stopPollingFeed];
    [[MTLocationManager sharedInstance] applicationClosed:sendReport];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    /*
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] startPollingFeed];
    [[MTLocationManager sharedInstance] applicationOpened:sendReport];*/
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL sendReport = [defaults boolForKey:kSendPositionReport];
    
    [[KmlElementDB sharedInstance] startPollingFeed];
    [[MTLocationManager sharedInstance] applicationOpened:sendReport];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	[tabBarController release];
    [window release];
    [super dealloc];
}


@end
